package com.tool.finances.lifestyle.data;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;

public class AccountProvider extends ContentProvider {

	private static final String DATABASE_NAME = "account.db";
	private static final int DATABASE_VERSION = 1;

	private static final String ACCOUNT_TABLE = "accountinfo";
	private static final String CATEGORY_TABLE = "category";
	private static final String PASSWORD_TABLE = "password";

	//
	private static final int ACCOUNT = 1;
	private static final int ACCOUNTDETAIL = 2;
	private static final int CATEGORY = 3;
	private static final int PASSWORD = 4;

	private DatabaseHelper mDataBaseHelper;
	private static final UriMatcher sUriMatcher;
	private static final String AUTHORITY = "com.tool.finances.lifestyle";

	private static final String ACCOUNT_TYPE = "vnd.android.cursor.dir/vnd.mgeek.moneybag.account";
	private static final String ACCOUNTDETAIL_TYPE = "vnd.android.cursor.dir/vnd.mgeek.moneybag.accountdetail";
	private static final String CATEGORY_TYPE = "vnd.android.cursor.dir/vnd.mgeek.moneybag.category";
	private static final String PASSWORD_TYPE = "vnd.android.cursor.dir/vnd.mgeek.moneybag.password";

	public static Uri ACCOUNT_CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + ACCOUNT_TABLE);
	public static Uri ACCCOUNT_DETAIL_URI = Uri.parse("content://" + AUTHORITY
			+ "/account");
	public static Uri CATEGORY_CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + CATEGORY_TABLE);
	public static Uri PASSWORD_URI = Uri.parse("content://" + AUTHORITY + "/"
			+ PASSWORD_TABLE);

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		int count;
		final SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT:
			count = db.delete(ACCOUNT_TABLE, selection, selectionArgs);
			break;
		case ACCOUNTDETAIL:
			final String accountDetailString = uri.getPathSegments().get(1);
			count = db.delete(ACCOUNT_TABLE, AccountType.Account.ACCOUNTDATE
					+ "="
					+ accountDetailString
					+ (!TextUtils.isEmpty(selection) ? " AND (" + selection
							+ ')' : ""), selectionArgs);
			break;
		case CATEGORY:
			count = db.delete(CATEGORY_TABLE, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		if (count > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
		return count;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT:
			return ACCOUNT_TYPE;
		case ACCOUNTDETAIL:
			return ACCOUNTDETAIL_TYPE;
		case CATEGORY:
			return CATEGORY_TYPE;
		case PASSWORD:
			return PASSWORD_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		long rowId;
		final SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT:
			rowId = db.insert(ACCOUNT_TABLE, null, values);
			break;
		case ACCOUNTDETAIL:
			rowId = db.insert(ACCOUNT_TABLE, null, values);
			break;
		case CATEGORY:
			rowId = db.insert(CATEGORY_TABLE, null, values);
			break;
		case PASSWORD:
			rowId = db.insert(PASSWORD_TABLE, null, values);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		if (rowId > 0) {
			final Uri noteUri = ContentUris.withAppendedId(uri, rowId);
			getContext().getContentResolver().notifyChange(noteUri, null);
			return noteUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		mDataBaseHelper = new DatabaseHelper(getContext());
		return true;
	}

	@SuppressWarnings("null")
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {

		final SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();

		Cursor cursor = null;
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT:
			if (TextUtils.isEmpty(sortOrder)) {
				sortOrder = AccountType.Account.ACCOUNTDATE + " desc";
			}
			cursor = db.query(ACCOUNT_TABLE, AccountType.Account.PROJECTION,
					selection, selectionArgs, null, null, sortOrder);
			break;
		case CATEGORY:
			sortOrder = "";
			cursor = db.query(CATEGORY_TABLE,
					AccountType.Account.CATEGORYPROECTION, selection,
					selectionArgs, null, null, sortOrder);
			break;
		case PASSWORD:
			cursor = db.query(PASSWORD_TABLE,
					AccountType.Account.PASSWORDPROJECTION, selection,
					selectionArgs, null, null, null);
		}
		// notification
		cursor.getCount();
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		final SQLiteDatabase db = mDataBaseHelper.getWritableDatabase();
		int count = 0;
		switch (sUriMatcher.match(uri)) {
		case ACCOUNT:
			count = db.update(ACCOUNT_TABLE, values, selection, selectionArgs);
			break;
		case PASSWORD:
			count = db.update(PASSWORD_TABLE, values, selection, selectionArgs);
			break;
		default:
			break;
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	private static class DatabaseHelper extends AccountDataBaseHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + ACCOUNT_TABLE + " ("
					+ AccountType.Account._ID + " INTEGER PRIMARY KEY,"
					+ AccountType.Account.ACCOUNTDATE + " DATETIME,"
					+ AccountType.Account.ACCOUNTMONEY + " INTEGER,"
					+ AccountType.Account.ACCOUNTTYPE + " NVARCHAR(50),"
					+ AccountType.Account.MONEYTYPE + " NVARCHAR(20),"
					+ AccountType.Account.INOROUT + " BOOLEAN,"
					+ AccountType.Account.COMMENT + " NVARCHAR(50)" + ");");

			db
					.execSQL("CREATE TABLE " + CATEGORY_TABLE + " (" + "_id"
							+ " INTEGER PRIMARY KEY,"
							+ AccountType.Account.CATEGORYTYPE
							+ " NVARCHAR(50)" + ");");
			final ContentValues values = new ContentValues();
			values.put(AccountType.Account.CATEGORYTYPE, "工资");
			db.insert(CATEGORY_TABLE, null, values);

			db
					.execSQL("CREATE TABLE " + PASSWORD_TABLE + " (" + "_id"
							+ " INTEGER PRIMARY KEY,"
							+ AccountType.Account.PASSWORDTYPE
							+ " NVARCHAR(50)" + ");");
			values.clear();
			values.put(AccountType.Account.PASSWORDTYPE, "123456");
			db.insert(PASSWORD_TABLE, null, values);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// db.execSQL("DROP TABLE IF EXISTS " + NEWS_TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + ACCOUNT_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + CATEGORY_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + PASSWORD_TABLE);
			onCreate(db);
		}
	}

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, ACCOUNT_TABLE, ACCOUNT);
		sUriMatcher.addURI(AUTHORITY, CATEGORY_TABLE, CATEGORY);
		sUriMatcher.addURI(AUTHORITY, "account/#", ACCOUNTDETAIL);
		sUriMatcher.addURI(AUTHORITY, PASSWORD_TABLE, PASSWORD);
	}
}
